package com.exle.security;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.exle.service.UserService;

public class JdbcFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	@Autowired
	private UserService userService;
	
	private PathMatcher pathMatcher = new AntPathMatcher();

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		FilterInvocation fi = (FilterInvocation) object;

		String url = fi.getRequestUrl();
//		System.out.println(url);
		// HttpServletRequest request = fi.getHttpRequest();

		// Instead of hard coding the roles lookup the roles from the database
		// using the url and/or HttpServletRequest
		// Do not forget to add caching of the lookup
		// String[] roles = new String[] { "ROLE_ADMIN", "ROLE_STUDENT",
		// "ROLE_TEACHER" };
		// String[] roles = new String[] {"ROLE_STUDENT"};

		String[] ss = url.split("/");
		String[] roles = userService.getRolesByUrl("/" + ss[1]);

		return SecurityConfig.createList(roles);
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return FilterInvocation.class.isAssignableFrom(clazz);
	}

}
